<?php

namespace app\web\controller;

use app\model\Attachment as AttachmentModel;

class Attachment extends Base
{
    public function attachment()
    {
        global $_G, $_P;
        $do = 'attachment';
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        switch ($op) {
            case 'display':
                return $this->lists();
                break;
            case 'del':
                return $this->del();
                break;
            default:
                return $this->lists();
                break;
        }
    }

    public function lists()
    {
        $model = new AttachmentModel();
        $list = $model->getList();
        return $list;
    }

    //删除
    public function del()
    {
        global $_G, $_P;
        $ids = $_P['ids'];
        if (!$ids) {
            $this->return_ajax_json(0, '参数错误');
        }
        $model = new AttachmentModel();
        $infos = $model->field('id,attachment')->where('id', 'in', $ids)->select();
        $pattern = '/^(http|https):\/\//i';
        foreach ($infos as $info) {
            $is_url = preg_match($pattern, $info['attachment']);
            if ($is_url) {
                $url = parse_url($info['attachment']);
                $url['path'] = str_replace('/99.jpg', '', $url['path']);
                $path = substr($url['path'], 1);
            } else {
                $path = $info['attachment'];
            }
            $del = oss_delete($path);
        }
        $del = $model->where('id', 'in', $ids)->delete();
        if ($del) {
            $this->return_ajax_json(1, '删除成功');
        } else {
            $this->return_ajax_json(0, '删除失败');
        }
    }

}
